package com.java46.gougoussowebs.util;

import javax.activation.CommandMap;
import javax.activation.MailcapCommandMap;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Date;
import java.util.Properties;

/**
 * 邮件发送核心类
 *
 */
public class SimpMailSender {
    /**
     * 发送Html邮件
     * @param mailSenderInfo
     * @return
     */
    public boolean sendeHtmlMail(MailSenderInfo mailSenderInfo){
        //判断是否需要验证
        MyVerification myVerification=null;
        Properties pro=mailSenderInfo.getProperties();//主机和端口
        System.out.println(mailSenderInfo.getPassword());
        //2、验证邮箱的账户和密码
        myVerification =new MyVerification(mailSenderInfo.getUserName(),mailSenderInfo.getPassword());
        //3、根据邮箱的会话属性和密码验证器，构建一个发送邮件的session对象
        Session sendMailSession=Session.getDefaultInstance(pro,myVerification);

        try {
            //4、通过session的会话创建一个邮件信息
            Message message=new MimeMessage(sendMailSession);
            //5、创建邮件发送者的地址
            Address from = new InternetAddress(mailSenderInfo.getFromAdress());
            //6、设置邮件的发送者 并且把地址设置到邮件当中
            message.setFrom(from);
            //7、创建接收者的地址
            Address to=new InternetAddress(mailSenderInfo.getToAdress());
            //8、Message.RecipientType.TO 表示接收者的类型 to:接收这的地址
            message.setRecipient(Message.RecipientType.TO,to);
            //9、发送邮件的主题
            message.setSubject(mailSenderInfo.getSubject());
            //10、设置发送邮件的时间
            message.setSentDate(new Date());
            //11、创建一个容器类
            Multipart multipart = new MimeMultipart();
            //12、包含html容器的body的标签
            BodyPart html =new MimeBodyPart();
            html.setContent(mailSenderInfo.getContent(),"text/html;charset=utf-8");
            multipart.addBodyPart(html);
            message.setContent(multipart);

            MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
            mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
            mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
            mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
            mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
            CommandMap.setDefaultCommandMap(mc);
            // 发送邮件
            Transport.send(message);
            System.out.println("恭喜你发送邮件成功！！");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("邮件发送失败！！");
            return false;
        }
    }
}
